package servlets;

import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import managers.DatabaseManager;

public class GetADImageServlet extends HttpServlet {

	private static final long serialVersionUID = 5062407575705398360L;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) {
		String idAdvertisement;
		InputStream inputStream;
		OutputStream outputStream;
		DatabaseManager databaseManager;
		Blob blob;
		databaseManager = new DatabaseManager();
		idAdvertisement = request.getParameter("idAdvertisement");
         try {
        	databaseManager.connect();
        	blob = databaseManager.getImageByIdAdvertisement(idAdvertisement);
     		databaseManager.closeConnection();
				// String headerKey = "Content-Disposition";
			    // String headerValue = String.format("attachment; filename=\"%s\"", "image.jpg");
			    // response.setHeader(headerKey, headerValue);
            response.setContentType("image/jpeg");
            response.setContentLength( (int) blob.length());
            inputStream = blob.getBinaryStream();
            outputStream = response.getOutputStream();
            byte buf[] = new byte[(int) blob.length()];
            inputStream.read(buf);
            outputStream.write(buf);
            outputStream.close();
        }
        catch(Exception ex) {
             ex.printStackTrace();
        }
    }

}
